import * as React from 'react';
import {useEffect} from 'react';
import Drawer from '@mui/material/Drawer';
import Button from '@mui/material/Button';
import List from '@mui/material/List';
import Divider from '@mui/material/Divider';
import ListItem from '@mui/material/ListItem';
import ListItemIcon from '@mui/material/ListItemIcon';
import ListItemText from '@mui/material/ListItemText';
import ListAltIcon from '@mui/icons-material/ListAlt';
import {
    Collapse,
    Dialog,
    DialogActions,
    DialogContent,
    DialogTitle,
    Fab,
    Grid,
    ListItemButton,
    TextField,
    ThemeProvider
} from "@mui/material";
import {ExpandLess, ExpandMore} from "@mui/icons-material";
import MyTable from "./MyTable";
import './LocalList.css';
import Avatar from "@mui/material/Avatar";
import {blue} from "@mui/material/colors";
import LibraryMusicIcon from "@mui/icons-material/LibraryMusic";
import ListItemAvatar from "@mui/material/ListItemAvatar";
import {createTheme} from "@mui/material/styles";
import PlayArrowOutlinedIcon from "@mui/icons-material/PlayArrowOutlined";
import AddCircleOutlineIcon from '@mui/icons-material/AddCircleOutline';
import PubSub from "pubsub-js";
import ClearIcon from '@mui/icons-material/Clear';
import DialogContentText from "@mui/material/DialogContentText";

const store = window.electron_store;

const theme = createTheme({
    palette: {
        myred: {
            main: '#ff0202',
            contrastText: 'white',
            light: '#ff0202'
        },
    },
});
const themeFab = createTheme({
    palette: {
        primary: {
            main: 'rgba(255,255,255,0)',
            contrastText: 'black',
            light: 'rgba(255,255,255,0)',
        },
    },
});
export default function LocalList() {
    const [state, setState] = React.useState({
        top: false,
        left: false,
        bottom: false,
        right: false,
    });
    const [localPlayList, setLocalPlayList] = React.useState([]);
    const [onlinePlayList, setOnlinePlayList] = React.useState([]);
    const [showList, setShowList] = React.useState({
        id:-1,
        musicList:[],
        name:''
    });
    const toggleDrawer = (anchor, open) => (event) => {
        init();
        if (event.type === 'keydown' && (event.key === 'Tab' || event.key === 'Shift')) {
            return;
        }

        setState({ ...state, [anchor]: open });
    };
    useEffect(() => {
        PubSub.subscribe('delOneSong',delOneSong);
    },[])
    const init = () => {
        //console.log('init');
        let localList = loadLocalList() || [];
        setLocalPlayList(localList);
    }
    const loadLocalList = () => {
        return store.get('localList');
    }
    const saveLocalList = (v) => {
         store.set('localList',v);
    }
    const [openLocal, setOpenLocal] = React.useState(true);

    const handleClickLocal = () => {
        setOpenLocal(!openLocal);
    };
    const [openOnline, setOpenOnline] = React.useState(false);

    const handleClickOnline = () => {
        setOpenOnline(!openOnline);
    };
    const handleClickList = (list) => {
        setShowList(list);
    }
    function addAll(){

        PubSub.publish("addAllMusic",{rows:showList.musicList})


    }
    function collectAll(){

        PubSub.publish("collectAllMusic",{rows:showList.musicList})


    }
    function delOneSong(msg,data) {
        //console.log(data)
        for (let list of localPlayList) {
            if(list.id === data.listID){
                let newList = [];
                for (let music of list.musicList) {
                    if(music.from !== data.from || music.id !== data.id || data.name !== music.name){
                        newList.push(music);
                    }
                }
                list.musicList = newList;
                setShowList(list);
                break;
            }
        }
        saveLocalList(localPlayList);
        setLocalPlayList(loadLocalList)
        // init();
    }
    function delLocalList(list){
        return (e) => {
            e.stopPropagation();
            setWarningSongList(list);
            setOpen(true);
        }
    }
    function addLocalList(e){
        e.stopPropagation();
        //console.log('add')
        setOpenAddDiag(true);

    }

        const [openAddDiag, setOpenAddDiag] = React.useState(false);

        const handleCloseAddDiag = () => {
            setOpenAddDiag(false);
        };
        let text = "";
        const handleChange = (e) => {
            text = e.target.value;
        };
        const handleCancle = () => {
          setOpenAddDiag(false);
        }
        const handleOK = () => {

            //console.log(text)
            let originList = store.get('localList') || [];
            originList.push({
                id:new Date().getTime(),
                name:text,
                musicList:[]
            })
            saveLocalList(originList);
            setLocalPlayList(originList);
            setOpenAddDiag(false);
        };
    function AddLocal() {
            return (
                <>
                    <Dialog open={openAddDiag} onClose={handleCloseAddDiag}>
                        <DialogTitle>请输入歌单名</DialogTitle>
                        <DialogContent>
                            <TextField
                                autoFocus
                                margin="dense"
                                id="name"
                                label="歌单名"
                                type="text"
                                fullWidth
                                variant="standard"
                                onChange={handleChange}
                            />
                        </DialogContent>
                        <DialogActions>
                            <Button onClick={handleCancle}>取消</Button>
                            <Button onClick={handleOK}>确定</Button>
                        </DialogActions>
                    </Dialog>
                </>
            );
    }
    const list = () => (
        <Grid
            container
            direction="row"
            justifyContent="center"
            alignItems="flex-start"
            sx={{maxHeight:655}}
        >
            <Grid item xs={3}>

                <List  component="nav" aria-label="mailbox folders">
                    <ListItem button className='playlist-title' onClick={handleClickLocal}>

                        <ListItemAvatar>
                            <Avatar sx={{ bgcolor: blue[100], color: blue[600] }}>
                                <LibraryMusicIcon />
                            </Avatar>
                        </ListItemAvatar>
                        <ListItemText primary="本地歌单" />

                        <Button className='playlist-add' color='inherit' onClick={addLocalList}>
                            <AddCircleOutlineIcon/>
                        </Button>
                        {openLocal ? <ExpandLess /> : <ExpandMore />}
                    </ListItem>

                    <Collapse in={openLocal} timeout="auto" unmountOnExit>
                        {localPlayList.map((r) => {
                            return(
                                <>
                                    <List component="div" className='listItem' key={r.id+'3'} disablePadding>

                                        <ListItem  key={r.id+'2'} button onClick={() => handleClickList(r)}>
                                            <ListItemIcon className='delListBtn' onClick={delLocalList(r)}>
                                                <ClearIcon />
                                            </ListItemIcon>
                                            <ListItemText key={r.id+'1'} primary={r.name} />
                                        </ListItem>
                                    </List>

                                    <Divider key={r.id+'4'}/>
                                </>
                            )
                        })}
                    </Collapse>
                    <ListItemButton className='playlist-title' onClick={handleClickOnline}>
                        <ListItemAvatar>
                            <Avatar sx={{ bgcolor: blue[100], color: blue[600] }}>
                                <LibraryMusicIcon />
                            </Avatar>
                        </ListItemAvatar>
                        <ListItemText primary="在线歌单" />
                        <Button className='playlist-add' color='inherit' onClick={addLocalList}>
                            <AddCircleOutlineIcon/>
                        </Button>
                        {openOnline ? <ExpandLess /> : <ExpandMore />}
                    </ListItemButton>
                    <Collapse in={openOnline} timeout="auto" unmountOnExit>
                        {onlinePlayList.map((r) => {
                            return(
                                <>
                                    <List component="div" className='listItem' key={r.id+'3'} disablePadding>
                                        <ListItem  key={r.id+'2'} button onClick={() => handleClickList(r)}>
                                            <ListItemIcon className='delListBtn' onClick={delLocalList(r)}>
                                                <ClearIcon />
                                            </ListItemIcon>
                                            <ListItemText key={r.id+'1'} primary={r.name} />
                                        </ListItem>
                                    </List>
                                    <Divider key={r.id+'4'}/>
                                </>
                            )
                        })}
                    </Collapse>

                </List>
            </Grid>
            <Grid item xs={9}>
                <Grid container justifyContent="flex-end" padding={1}>
                    <ThemeProvider theme={theme}>
                        <Button className='playAllBtn' variant="contained" color='myred' onClick={addAll}><PlayArrowOutlinedIcon/>播放全部</Button>
                        <Button sx={{marginLeft:5,marginRight:5}} variant="outlined" color='myred' onClick={collectAll}>添加全部</Button>
                    </ThemeProvider>
                </Grid>
                <MyTable listID={showList.id} rows={showList.musicList}/>
            </Grid>


        </Grid>
    );
    const [open, setOpen] = React.useState(false);
    const [warningSongList, setWarningSongList] = React.useState({
        id:-1,
        name:'',
        musicList:[]
    });


    const handleClose = () => {
        setOpen(false);
    };
    const handleOk = () => {
        let newLocalPlayList = [];
        for (let list of localPlayList) {
            if(list.id !== warningSongList.id){
                newLocalPlayList.push(list);
            }
        }
        setLocalPlayList(newLocalPlayList);
        saveLocalList(newLocalPlayList);
        setOpen(false);
    }
    function WarningDelList(){
        return(
            <div>
                <AddLocal/>
                <Dialog
                    open={open}
                    onClose={handleClose}
                    aria-labelledby="alert-dialog-title"
                    aria-describedby="alert-dialog-description"
                >
                    <DialogTitle id="alert-dialog-title">
                        {"确定删除该歌单吗?"}
                    </DialogTitle>
                    <DialogContent>
                        <DialogContentText id="alert-dialog-description">
                            即将删除歌单:{warningSongList.name}
                        </DialogContentText>
                    </DialogContent>
                    <DialogActions>
                        <Button onClick={handleClose}>放弃</Button>
                        <Button onClick={handleOk} autoFocus>
                            确定
                        </Button>
                    </DialogActions>
                </Dialog>
            </div>
        )
    }
    return (
        <div className='playlist-fab'>
            <WarningDelList/>
            {['bottom'].map((anchor) => (
                <React.Fragment key={anchor}>
                    <ThemeProvider theme={themeFab}>
                        <Fab color="primary"  ariant="extended" onClick={toggleDrawer(anchor, true)}>
                            <ListAltIcon/>
                        </Fab>
                    </ThemeProvider>

                    <Drawer
                        anchor={anchor}
                        open={state[anchor]}
                        onClose={toggleDrawer(anchor, false)}
                    >
                        {list()}
                    </Drawer>
                </React.Fragment>
            ))}
        </div>
    );
}